from rest_framework import serializers
from rest_framework.viewsets import ModelViewSet
from labor_price.models import Position
from api.Department.view import DepartmentSerializer
import json
from rest_framework.decorators import action
from rest_framework.response import Response
class PositionSerializer(serializers.ModelSerializer):
    department_id = serializers.IntegerField()
    # department = serializers.SlugRelatedField(slug_field="name", read_only=True)
    # codinga = serializers.SlugRelatedField(slug_field="coding", read_only=True)
    department = DepartmentSerializer(read_only=True)
    class Meta:
        model=Position
        fields='__all__'

class PositionView(ModelViewSet):
    queryset = Position.objects.all()  # 查询集
    serializer_class = PositionSerializer  # 序列化器

    @action(methods=['get'], detail=False)
    def batch_del(self, request):
        del_list = request.GET.get('del_list')
        del_list = json.loads(del_list)
        try:
            for i in (del_list):
                Department.objects.get(id=i).delete()
        except:
            return Response({'msg': "批量删除失败", 'code': 400, 'data': '存在关联数据；不允许删除'})
        return Response({'msg': "批量删除成功", 'code': 200})